package com.etc.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.etc.entity.Message;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public   class MsgSend {
    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static final String accessKeyId = "LTAI4FvJQfoFCvjMPA3S6UkW";
    static final String accessKeySecret = "oEXeX997v5zghnsfF6gwH7cXmW2UuT";

    private Logger logger= Logger.getLogger(MsgSend.class);

    private  MsgSend (){};
    private static MsgSend megSend;

    public static MsgSend getUtil(){
        if(null == megSend){
            synchronized (MsgSend.class){
                if(null == megSend){
                    megSend = new MsgSend();
                }
            }
        }
        return megSend;
    }
    //邮箱注入
    @Autowired
    private JavaMailSender javaMailSender;

    private String emailfrom="2099362264@qq.com";


    //短信发送
    public  boolean sendSms(Message message) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(message.getPhonenum());//这里手机号是假的
        //必填:短信签名-可在短信控制台中找到
        request.setSignName("浅时光");
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode("SMS_184115849");//这里模板编号是假的
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为

        request.setTemplateParam("{'code':"+ message.getCode()+"}");//这里手机号是假的

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId("yourOutId");
        SendSmsResponse response; QuerySendDetailsResponse querySendDetailsResponse=null;
        try {
            //hint 此处可能会抛出异常，注意catch
          response = acsClient.getAcsResponse(request);
          querySendDetailsResponse = querySendDetails(response.getBizId());
        }catch (ClientException e) {
            //发送失败返回false;
            logger.info(message.getPhonenum()+"发送失败"+ message.getCode());
           return false;
        }
        logger.info("发送成功");
        //发送成功返回true;
        return true;
    }

    public  QuerySendDetailsResponse querySendDetails(String bizId) throws ClientException {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象
        QuerySendDetailsRequest request = new QuerySendDetailsRequest();
        //必填-号码
        request.setPhoneNumber("17859989913");
        //可选-流水号
        request.setBizId(bizId);
        //必填-发送日期 支持30天内记录查询，格式yyyyMMdd
        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        request.setSendDate(ft.format(new Date()));
        //必填-页大小
        request.setPageSize(10L);
        //必填-当前页码从1开始计数
        request.setCurrentPage(1L);

        //hint 此处可能会抛出异常，注意catch
        QuerySendDetailsResponse querySendDetailsResponse = acsClient.getAcsResponse(request);

        return querySendDetailsResponse;
    }
     //发送邮箱
     public  boolean sendMail(JavaMailSender javaMailSender, String emailfrom, Message message){
         System.out.println("进入发送邮箱"+ message);
         System.out.println(javaMailSender);
         MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
         MimeMessageHelper mMessageHelper;
         Properties prop = new Properties();
         String from;
         try {
             //从配置文件中拿到发件人邮箱地址，改成固定
//         prop.load(this.getClass().getResourceAsStream("/mail.properties"));
//            System.out.println("进入catch");
             from = "2099362264@qq.com";
             mMessageHelper=new MimeMessageHelper(mMessage,true);
             mMessageHelper.setFrom(from);//发件人邮箱
             mMessageHelper.setTo(message.getToemail());//收件人邮箱
             mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题
             mMessageHelper.setText("<p color='blue'>您找回的密码为"+ message.getCode()+"</p><br/>",true);//邮件的文本内容，true表示文本以html格式打开
//            File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片
//            FileSystemResource resource=new FileSystemResource(file);
//            mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用
//            mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件
             javaMailSender.send(mMessage);//发送邮件
         } catch (MessagingException e) {
             e.printStackTrace();
            logger.info("邮箱发送失败"+ message.getToemail()+ message.getCode());
             return false;
         } catch (Exception e) {
             e.printStackTrace();  System.out.println("进入异常");
             logger.info("邮箱发送失败"+ message.getToemail()+ message.getCode());
             return false;
         }
         logger.info("发送成功");
         return true;
     }
}
